#include "..\\include\Lib_Clara.h"
#include "..\\include\Dir.h"
#include "..\\include\cfg_items.h"
#include "lang.h"
#include "conf_loader.h"
#include "config_data.h"
#include "structs.h"
#include "main.h"
#include "functions.c"
#include "board.cpp"
#define OPEN_PLAYER_EVENT 993

int TerminateElf(void * ,BOOK* book)
{
  FreeBook(book);
  return(1);
}

int ShowAuthorInfo(void *mess ,BOOK* book)
{
  MSG * msg = (MSG*)mess;
  MessageBox(0x6fFFFFFF,STR("Advanced Player v4.2\n(c)mc_kibel\nThanks to all AdvPlayer's modders!"),0, 1 ,5000,msg->book);
  return(1);
}

static int ReconfigElf(void *mess ,BOOK *book)
{
  RECONFIG_EVENT_DATA *reconf=(RECONFIG_EVENT_DATA *)mess;
  int result=0;
  if (wstrcmpi(reconf->path,successed_config_path)==0 && wstrcmpi(reconf->name,successed_config_name)==0)
  {
        InitConfig();
        result=1;
  }
  return(result);
}



const PAGE_MSG HW_PageEvents[]@ "DYN_PAGE" ={
  ELF_TERMINATE_EVENT , TerminateElf,
  ELF_SHOW_INFO_EVENT  , ShowAuthorInfo,
  ELF_RECONFIG_EVENT, ReconfigElf,
  OPEN_PLAYER_EVENT, OnOpenPlayer,
  UI_MEDIAPLAYER_AUDIO_PLAYING_TIME_EVENT_TAG,  onPlayTimer,
  NIL_EVENT_TAG, NULL
};
PAGE_DESC base_page ={"HW_BasePage",0,HW_PageEvents};

void elf_exit(void)
{
  kill_data(&ELF_BEGIN, (void(*)(void*))mfree_adr());
}

TRACK_DESC * TrackDesc_Get(BOOK *bk)
{
  if (bk)
  {
    if (platform==DB2010)
    {
      BOOK_PLAYER_2010 *bkp=(BOOK_PLAYER_2010*)bk;
      TRACK_DESC *track_desc=new TRACK_DESC;
      memset(track_desc,0,sizeof(TRACK_DESC));
      wchar_t *path=bkp->dsc->path;
      wchar_t *name=bkp->dsc->name;
      track_desc->path=new wchar_t[wstrlen(path)+1];
      wstrcpy(track_desc->path,path);
      track_desc->name=new wchar_t[wstrlen(name)+1];
      wstrcpy(track_desc->name,name);
      track_desc->fulltime=bkp->dsc->fulltime;
      if (bkp->tracks_count)
      {
        track_desc->tracks_count=bkp->tracks_count;
      }
      else
      {
        track_desc->tracks_count=bkp->tracks_count2;
      }
      if (bkp->pos>10000)
      {
        track_desc->pos=bkp->pos2+1;
      }
      else
      {
        track_desc->pos=bkp->pos+1;
      }
      return track_desc;
    }
    else if (platform==DB2020)
    {
      BOOK_PLAYER_2020 *bkp=(BOOK_PLAYER_2020*)bk;
      TRACK_DESC *track_desc=new TRACK_DESC;
      memset(track_desc,0,sizeof(TRACK_DESC));
      wchar_t *path=bkp->dsc->path;
      wchar_t *name=bkp->dsc->name;
      track_desc->path=new wchar_t[wstrlen(path)+1];
      wstrcpy(track_desc->path,path);
      track_desc->name=new wchar_t[wstrlen(name)+1];
      wstrcpy(track_desc->name,name);
      track_desc->fulltime=bkp->dsc->fulltime;
      //track_desc->fulltime=bkp->time;
      track_desc->tracks_count=bkp->tracks_count;
      track_desc->pos=bkp->pos2+1;
      return track_desc;
    }
  }
  return 0;
};


int onPlayTimer(void *message,BOOK* bk)
{
  if (FindBook(isAudioPlayerBook()))
  {
    PLAY_TIME *pl=(PLAY_TIME*)message;
    CurrentTime=(pl->hour * 60)+ ((pl->min * 60) + pl->sec);
  }
  return 0;
};

void GetTags (void)
{
  ntrack=TrackDesc_Get(FindBook(isAudioPlayerBook()));
  Tpath = ntrack->path;
  Tname = ntrack->name;
  MetaData_Desc = MetaData_Desc_Create(Tpath, Tname);
  
  TimeLeft = ntrack->fulltime-CurrentTime;
  MIN_TimeLeft=TimeLeft/60;
  SEC_TimeLeft=TimeLeft%60;
  snwprintf(TimeLeft1,SID_ANY_LEN,L"-%02d:%02d",MIN_TimeLeft,SEC_TimeLeft);
  ttl = MetaData_Desc_GetTags(MetaData_Desc,TAG_TITLE);
  artst = MetaData_Desc_GetTags(MetaData_Desc,TAG_ARTIST);
  
  if (wstrlen(ttl)==43) //43 = empty!
    ttl = Tname;
  
  MetaData_Desc_Destroy (MetaData_Desc);
}



void DrawProgress(int bColor, int cColor, int oColor, RECT rect, int progress, int time, signed int PlusY, int type)
{
  if (!type)
  {
    DrawRect(rect.x1+1,rect.y1+PlusY,rect.x2-1,rect.y1+PlusY+1, bColor, bColor);
    DrawRect(rect.x2-1,rect.y1+PlusY,rect.x2,rect.y2+PlusY, bColor, bColor);    
    DrawRect(rect.x1,rect.y1+PlusY,rect.x1+1,rect.y2+PlusY, bColor, bColor); 
    DrawRect(rect.x1+1,rect.y2+PlusY-1,rect.x2-1,rect.y2+PlusY, bColor, bColor);    
    DrawRect(rect.x1+1,rect.y1+1+PlusY,rect.x2-1,rect.y2-1+PlusY, oColor, oColor);
    float Length;
    float CurLength=(float)progress;
    float inLength=(float)time;
    float Procent=(float)CurLength/inLength;
    float size=(float)((float)rect.x2-(float)rect.x1);
    float start = (float)rect.x1;
    Length = start+((Procent)*size);
    DrawRect(rect.x1+1, rect.y1+1+PlusY,(int)Length - 1,rect.y2-1+PlusY,cColor,cColor);
  }
};
void WaitingForPlayer (u16 tmr , void *)
{
  if (Display_GetTopBook(0) == FindBook(isAudioPlayerBook()))
  {
    Timer_Kill(&WaitingTimer);
    ftimer=Timer_Set(10,onRedrTimer,0);
  }
  else
  {
    Timer_ReSet(&WaitingTimer,2000,WaitingForPlayer,0);
  }
}
  
void onRedrTimer (u16 tmr , void *)
{
  if (Display_GetTopBook(0) != FindBook(isAudioPlayerBook()) && Display_GetTopBook(0) != FindBook(isRunned) && Display_GetTopBook(0) != FindBook(isScreenSaverBook()))
  {
    Timer_Kill(&ftimer);
    m_smilgc=NULL;
    GVI_Delete_GVI_Object( &m_br );
    GC_FreeGC( m_hMGC );
    tmrwrk=0;
    WaitingTimer = Timer_Set(2000,WaitingForPlayer,0);
  }
  else 
  {
    if (play)
    {
      DispObject_InvalidateRect(DO,0);
    }
    Timer_ReSet(&ftimer,(1000/fps),onRedrTimer,0);
  }
}
  
void walkman_Redraw(DISP_OBJ* DO,int a,int b,int c)
{
  if(m_smilgc==NULL)
  {
    m_br=GVI_CreateSolidBrush(0xFF000000);
    m_hMGC = GC_CreateMemoryGC( gcmem_xsize, 320, 16, 0,0,0 );
    CANVAS_Get_GviGC( m_hMGC->pcanvas ,&m_smilgc);
    GVI_FillRectangle(m_smilgc, 0,0, gcmem_xsize,320, m_br);
    GC_PutChar(m_hMGC,0,0,0,0, image[0].ImageID);
  }
  GVI_GC gvigc = NULL;
  CANVAS_Get_GviGC(gc->pcanvas, &gvigc);
  GVI_BitBlt(gvigc,0,0,240,320,m_smilgc,(240*kl),0,204, 0,  2,  3);
  PLAY_STATE *wb=(PLAY_STATE*)FindBook(isAudioPlayerBook()); 
  play= (int)wb->status;
  if (play == 1)
  {
    if (kl > ((gcmem_xsize/screen_width)-2))
      kl=0;
    else
      kl++;
  }
  GC_PutChar(GCanvas, 0, 0, 0, 0, image[1].ImageID);
  GC_PutChar(GCanvas, 0, 0, 0, 0, image[2].ImageID);
  GC_PutChar(GCanvas, 0, 289, 0, 0, image[2].ImageID);
  
  int p=(int)wb->preset; 
  GC_PutChar(GCanvas,1, 55, 0, 0, wb->preset<5 ? imagep[p].ImageID : imagep[5].ImageID);
  GC_PutChar(GCanvas,31, 55, 0, 0, wb->ShuffleMode==1 ? image[3].ImageID : image[4].ImageID);
  GC_PutChar(GCanvas,61, 55, 0, 0, wb->RepeatMode==1 ? image[5].ImageID : image[6].ImageID);
  BOOK *bk = Display_GetTopBook(0);
  BOOK_PLAYER_2020 *bkp=(BOOK_PLAYER_2020*)(bk);
  GetTags();
  SetFont(0x19);
  {
    if (bk==FindBook(isScreenSaverBook()))
    {
      tleft = Str2ID(TimeLeft1,0,SID_ANY_LEN);
    }
    else
    {
      wchar_t buf[16];
      int te=bkp->dsc->fulltime - bkp->time;
      int  m=te/60;int sek=te%(60 * m);
      snwprintf(buf,15,  L"-%02d:%02d",m,sek);
      tleft = Str2ID(buf,0,SID_ANY_LEN);
    }
    title = Str2ID(ttl,0,SID_ANY_LEN);
    artist = Str2ID(artst,0,SID_ANY_LEN);
    DrawString(title,0,0x1C,4,0xBA,0x15,0,0,0xFFFFFFFF,0x00000000);
    DrawString(artist,0,0x1C,0x1A,0xBA,0x2A,0,0,0xFFFFFFFF,0x00000000);
    DrawString(tleft,1,0xAA,0x33,0xEC,0x50,0,0,0xFFFFFFFF,0x00000000);
    TextFree(title);
    TextFree(artist);
    TextFree(tleft);
  }
  RECT rect;
  rect.x1=0;
  rect.x2=240;
  rect.y1=0x2E;
  rect.y2=0x2E+5;
  DrawProgress(0x00ffffff,0xFFffffff, 0xFF9a9a9a, rect, bkp->time, ntrack->fulltime, 0, 0); 
}


int OnOpenPlayer (void* msg, BOOK* book)
{
  DO=(DISP_OBJ*)msg;
  DISP_DESC_SetOnRedraw(DispObject_GetDESC(DO), walkman_Redraw);
  GUI *mpgui;
  mpgui=(GUI*)((MediaPlayerBook*)FindBook(isAudioPlayerBook()))->gui;
  MediaPlayer_SoftKeys_SetText(mpgui,50,STR(choosestyle_s));
  MediaPlayer_SoftKeys_SetAction(mpgui,50,RunGUI);
  MediaPlayer_SoftKeys_SetItemAsSubItem(mpgui,20,50);
  MediaPlayer_SoftKeys_AddHelpStr(mpgui,50,STR(choosestyle_helpstr));
  if (STATUSBAR_ENABLED == 0)
  {
    GUI *g;
    g=FindGuiInBook(Display_GetTopBook(0),"MediaPlayer_Audio");
    GUIObject_SetStyle(g,3);
    GUIObject_SetTitleType(g, 1);
    GUIObject_SetTitleText (g, STR("AdvPlayer"));
  }
  GCanvas = get_DisplayGC();
  gc = get_DisplayGC();
  if (tmrwrk==0)
  {
    ftimer=Timer_Set(10,onRedrTimer,0);
    tmrwrk++;
  }
  return 0;
}

void RegisterImages (void)
{
    RegisterImage(&image[1] ,confpath,L"upbar.png");
    RegisterImage(&image[2] ,confpath,L"stripes.png");
    RegisterImage(&imagep[0] ,confpath,presets_files[0]);  
    RegisterImage(&imagep[1] ,confpath,presets_files[1]); 
    RegisterImage(&imagep[2] ,confpath,presets_files[2]); 
    RegisterImage(&imagep[3] ,confpath,presets_files[3]); 
    RegisterImage(&imagep[4] ,confpath,presets_files[4]); 
    RegisterImage(&imagep[5] ,confpath,presets_files[5]); 
    RegisterImage(&image[3] ,confpath,L"shuffle_on.png");
    RegisterImage(&image[4] ,confpath,L"shuffle_off.png");
    RegisterImage(&image[5] ,confpath,L"repeat_on.png");
    RegisterImage(&image[6] ,confpath,L"repeat_off.png");
    RegisterImage(&image[0] ,confpath,skin_to_run);
}

void UnregisterImages (void)
{
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,image1[0].ImageHandle,0,0,image1[0].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,image[0].ImageHandle,0,0,image[0].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,image[1].ImageHandle,0,0,image[1].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,image[2].ImageHandle,0,0,image[2].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,imagep[0].ImageHandle,0,0,imagep[0].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,imagep[1].ImageHandle,0,0,imagep[1].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,imagep[2].ImageHandle,0,0,imagep[2].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,imagep[3].ImageHandle,0,0,imagep[3].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,imagep[4].ImageHandle,0,0,imagep[4].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,image[3].ImageHandle,0,0,image[3].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,image[4].ImageHandle,0,0,image[4].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,image[5].ImageHandle,0,0,image[5].ImageID,1,&error_code);
    REQUEST_IMAGEHANDLER_INTERNAL_UNREGISTER(SYNC,image[6].ImageHandle,0,0,image[6].ImageID,1,&error_code);
}


void onCloseMSBook(BOOK * book)
{
  if (book)
  {
    UnregisterImages ();
    Timer_Kill(&WaitingTimer);
    if (FindBook(isAudioPlayerBook()))
    {
      FreeBook(FindBook(isAudioPlayerBook()));
      UI_Event (RETURN_TO_STANDBY_EVENT);
      MessageBox (0x6Fffffff,STR(exitinfo),0,1,4000,0);
    }
    SUBPROC(elf_exit);
  }
}

void CreateMSBook(void)
{
  MyBOOK * MSBook= new MyBOOK;
  memset(MSBook,0,sizeof(MyBOOK));
  CreateBook((BOOK*)MSBook,onCloseMSBook,&base_page,"AdvPlayer",-1,0);
  MMSBook=MSBook;
}

int GetPlatform (void)
{
  switch (GetChipID())
  {
  case 0x7100:
  case 0x8000:
  case 0x8040:
    return (DB2010);
  case 0x9900:
    return (DB2020);
  }
  return 0;
}

int GetSkinsCount (const wchar_t *skinspath)
{
  FSTAT fst;
  wchar_t tmp_fname[16];
  int file_count = 1;
  snwprintf (tmp_fname,255,L"%d.png",file_count);
  while (fstat( skinspath, tmp_fname, &fst ) == 0)
  {
    file_count++;
    snwprintf (tmp_fname,255,L"%d.png",file_count);
  }
  return (file_count-1);
}

int main (void)
{
  if (FindBook(isRunned))
  {
    MessageBox(0x6fFFFFFF,STR(workingmsg),0, 1 ,3000,0);
  }  
  else 
  {
    InitConfig();
    CreateMSBook();
    platform = GetPlatform();
    screen_width = Display_GetWidth( 0 );
    snwprintf (skin_to_run,255,L"%d.png",skinimg);  
    RegisterImages();
    gcmem_xsize=GetImageWidth( image[0].ImageID );
  }
  return(0);
}
